//交互操作

const child_process = require('child_process');
const util = require('util');
const execFile = util.promisify(child_process.execFile);

const exec = child_process.exec;
// 引入shell.js等依赖
const shell = require('shelljs');
const { echo } = shell;//打印
const { exit } = shell;//退出命令
const inquirer = require('inquirer');//交互
const chalk = require('chalk');//颜色
const ora = require('ora');//loading
const commander = require("commander");//判断
const program = new commander.Command();
const log = console.log;
program.version('0.0.1');
//定义pya-deploy项目的目录
const pay_deploy_dir = shell.pwd();
const buffer_size = 20 * 1024 * 1024;//执行子进程，stdout的最大缓存大小

// 测试命令 https://gitee.com/q-_-p/node_shell/blob/master/index.js
// program
//  .option('-d, --debug', 'output extra debugging')

//  .option('-s, --small', 'small pizza size')
//  .option('-p, --pizza-type <type>', 'flavour of pizza');
// var prompt = inquirer.createPromptModule();  

async function git_clone(parent_dir, git_address) {
    //设置 sh 命令执行的参数
    let args = [pay_deploy_dir + "/shell/git_clone.sh"];
    //设置环境变量
    let environment = { 'git_address': git_address, ...process.env };//process.env.clone_result

    let options = { cwd: parent_dir, env: environment, shell: '/bin/bash', maxBuffer: buffer_size };
    // //阻塞的方式
    let result = await execFile('sh', args, options);
    // console.log(environment.clone_result);
    const { stdout,stderr,code } = result;

    console.log(stdout);//输出执行结果
    console.log(stderr);
    console.log(code);
}

function git_clone2(parent_dir, git_address) {
    //设置 sh 命令执行的参数
    let cmd = "sh " + pay_deploy_dir + "/shell/git_clone.sh";
    //设置环境变量
    let environment = { 'git_address': git_address, ...process.env };
    let options = {async: false, silent: false, cwd: parent_dir, env: environment, shell: '/bin/bash', maxBuffer: buffer_size };
    const result = shell.exec(cmd, options);
    console.info(result.stdout);
    console.info(result.stderr);
    console.info(result.code);
    // let cat=result.toEnd('git_result.txt').cat('git_result.txt');
    console.info(new Date());
}
function git_clone3(parent_dir, git_address) {
    //设置 sh 命令执行的参数
    let cmd = "git clone " + git_address;
    //设置环境变量
    // let environment = { 'git_address': git_address, ...process.env };
    let options = { silent: false, cwd: parent_dir, maxBuffer: buffer_size };
    let stdout = shell.exec(cmd, options);
    console.log(stdout.stdout);//输出执行结果
    console.log(stdout.stderr);//输出执行结果
    console.log(stdout.code);
    // console.log(stdout.tail());

}

async function git_clone4(parent_dir, git_address) {
    let options = { cwd: parent_dir, maxBuffer: buffer_size };
    let result= await execFile('git', ['clone', git_address], options);
    const { stdout } =result;
    console.log(stdout);//输出执行结果
    return;
}

const spawn = require('child_process').spawn;

function git_clone5(parent_dir, git_address) {
    let options = { async: true, cwd: parent_dir,silent:true, shell: '/bin/bash' };
    const git = spawn('git', ['clone', git_address], options);
    git.stdout.on('data', (data) => {
        console.log('stdout:' + data.toString());
        console.log(`stdout: ${data}`);
    });
    
    git.stderr.on('data', (data) => {
        console.log(`stderr: ${data}`);
    });

    git.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
    });

}

function git_clone6(parent_dir, git_address) {

    //设置 sh 命令执行的参数
    let args = [pay_deploy_dir + "/shell/git_clone.sh"];
    //设置环境变量
    let environment = { 'git_address': git_address, ...process.env };

    let options = { cwd: parent_dir, env: environment, shell: '/bin/bash', maxBuffer: buffer_size };

    child_process.execFile('sh', args, options, function (error, stdout, stderr) {
        if (error) {
            throw error;
        }
        console.log(stdout);
    });
}




/**执行命令 git clone
 *@param git_address git地址
 */
 function git_clone7(parent_dir, git_address) {
    // 判断当前环境是否安装支持git
    const git = shell.which('git');
    // 如果支持开启用户输入框
    if (git) {
        // 执行克隆命令
        let args = ['clone ' + git_address];
        let options = { async: false, cwd: parent_dir, shell: '/bin/bash' };
        //const { stdout } = await execFile('git', args, options);
        let git_stdout = child_process.execFile('git', args, options, function (error, stdout, stderr) {
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            // shell.echo('$clone_result')
            if (error !== null) {
                console.log('exec error: ' + error);
                shell.echo('克隆失败，请检查克隆地址是否存在');
                shell.exit(1);
            } else {
            }
        });
        console.info(new Date());

        // git_stdout.on('data', data => console.log('stdout: ', data));
        git_stdout.on('data', (data) => {
            console.log('stdout:' + data.toString());
            console.log(`stdout: ${data}`);
        });

        console.warn('stdout: ', git_stdout);

    }
    // 不支持则提示用户下载 git
    else {
        shell.echo('请先下载安装git');
        shell.exit(1);
    }
}




/**执行命令 git clone
 *@param git_address git地址
 */
 function git_clone8(parent_dir, git_address) {
    // 判断当前环境是否安装支持git
    const git = shell.which('git');
    // 如果支持开启用户输入框
    if (git) {
        // 执行克隆命令
        let options = { async: false, cwd: parent_dir, shell: '/bin/bash' };
        let git_stdout = shell.exec('git clone '+ git_address, options, function (code, stdout, stderr) {
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            // shell.echo('$clone_result')
            if (code == 0) {
            } else {
                console.log('exec error: ' + stderr);
                shell.echo('克隆失败，请检查克隆地址是否存在');
                shell.exit(1);
            }
        });
        console.info(new Date());

        // git_stdout.on('data', data => console.log('stdout: ', data));
        git_stdout.on('data', (data) => {
            console.log('stdout2:' + data.toString());
            console.log(`stdout2: ${data}`);
        });

        console.warn('stdout: ', git_stdout);

    }
    // 不支持则提示用户下载 git
    else {
        shell.echo('请先下载安装git');
        shell.exit(1);
    }
}

/**执行命令 git clone
 *@param git_address git地址
 */
 function git_clone9(parent_dir, git_address) {
    // 判断当前环境是否安装支持git
    const git = shell.which('git');
    // 如果支持开启用户输入框
    if (git) {
        // 执行克隆命令
        let cmd='git clone '+ git_address;
        let options = { async: false, cwd: parent_dir, 
            shell: '/bin/bash' 
        };
        let result = shell.exec(cmd, options);
        
        console.info(result.stdout)
        console.info(result.stderr)
        console.info(result.code)
        console.info(new Date());

    }
    // 不支持则提示用户下载 git
    else {
        shell.echo('请先下载安装git');
        shell.exit(1);
    }
}



let parent_dir = '/deploy/src/', git_address = 'https://git.visioners.cn/charge/pay-deploy.git';
git_clone(parent_dir, git_address);
// git_clone2(parent_dir,git_address);
// git_clone3(parent_dir,git_address);
// git_clone4(parent_dir,git_address);
// git_clone5(parent_dir, git_address);
// git_clone6(parent_dir,git_address);
// git_clone7(parent_dir,git_address);
// git_clone8(parent_dir,git_address);
// git_clone9(parent_dir,git_address);
console.info(new Date());


//
function child_script() {
    const cp = require("child_process")
    const { resolve } = require("path");
    (async () => {
        const script = resolve(__dirname, "../crawler/tushuguan");//脚本路径

        const child = cp.fork(script, [])

        let invoked = false

        child.on('error', err => {
            if (invoked) return
            invoked = true
            console.log(err)
        })
        child.on("exit", code => {
            if (invoked) return
            else invoked = false

            let err = code === 0 ? null : new Error('exit code' + code)
            console.log(err)
        })
        //时间监听
        child.on('message', data => {
            let result = data.result
            console.log(result)
        })
    })()
}

